<template>
  <div class="navbar">
    <div class="left-side">
      <a-space>
        <img alt="logo" src="@/assets/images/logo.png" />
        <icon-menu-fold
          v-if="!keepDesktop && !topMenu && appStore.device === 'mobile'"
          style="font-size: 22px; cursor: pointer"
          @click="toggleDrawerMenu"
        />
      </a-space>
    </div>
    <div class="center-side">
      <Menu v-if="topMenu" />
    </div>
    <ul class="right-side">
      <!--<li>
				<a-tooltip :content="
            theme === 'light'
              ? $t('settings.navbar.theme.toDark')
              : $t('settings.navbar.theme.toLight')
          ">
					<a-button class="nav-btn" type="outline" :shape="'circle'" @click="handleToggleTheme">
						<template #icon>
							<icon-moon-fill v-if="theme === 'dark'" />
							<icon-sun-fill v-else />
						</template>
					</a-button>
				</a-tooltip>
			</li>-->
      <li>
        <a-tooltip
          :content="
            isFullscreen
              ? $t('settings.navbar.screen.toExit')
              : $t('settings.navbar.screen.toFull')
          "
        >
          <a-button
            class="nav-btn"
            type="outline"
            :shape="'circle'"
            @click="toggleFullScreen"
          >
            <template #icon>
              <icon-fullscreen-exit v-if="isFullscreen" />
              <icon-fullscreen v-else />
            </template>
          </a-button>
        </a-tooltip>
      </li>
      <li>
        <a-dropdown trigger="click">
          <div :style="{ cursor: 'pointer' }">
            <a-avatar :size="32" :style="{ marginRight: '8px' }">
              <img alt="avatar" :src="avatar" v-if="userStore.avatar" />
              <img alt="avatar" src="@/assets/images/1.png" v-else />
            </a-avatar>
            {{ userStore.nickname }}
          </div>
          <template #content>
            <a-doption>
              <a-space @click="handleLogout">
                <icon-export />
                <span>
                  {{ $t('messageBox.logout') }}
                </span>
              </a-space>
            </a-doption>
            <a-doption>
              <a-space @click="uploadShow = true">
                <icon-pen-fill />
                <span> 修改密码 </span>
              </a-space>
            </a-doption>
          </template>
        </a-dropdown>
      </li>
    </ul>
  </div>
  <!-- 修改密码弹窗 -->
  <a-modal
    class="df"
    v-model:visible="uploadShow"
    @cancel="uploadCancel"
    :on-before-ok="uploadCheck"
    :mask-closable="false"
    unmountOnClose
    width="450px"
  >
    <template #title> 修改密码 </template>
    <a-form ref="uploadModel" :rules="uploadRules" :model="uploadForm">
      <a-row style="margin-bottom: 16px">
        <a-form-item field="oldPassword" label="旧密码">
          <a-input-password
            v-model="uploadForm.oldPassword"
            placeholder="请输入旧密码"
            :style="{ width: '320px' }"
            :defaultVisibility="false"
            allow-clear
          />
        </a-form-item>
        <a-form-item field="newPassword" label="新密码">
          <a-input-password
            v-model="uploadForm.newPassword"
            placeholder="请输入新密码"
            :style="{ width: '320px' }"
            :defaultVisibility="false"
            allow-clear
          />
        </a-form-item>
        <a-form-item field="nnewPassword" label="确认密码">
          <a-input-password
            @input="erpassfn"
            v-model="uploadForm.nnewPassword"
            placeholder="请输入新密码"
            :style="{ width: '320px' }"
            :defaultVisibility="false"
            allow-clear
          />
        </a-form-item>
        <div class="lc" v-if="byyshow"> 两次输入密码不一致,请重新输入</div>
      </a-row>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
  import { computed, ref, inject } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { useDark, useToggle, useFullscreen } from '@vueuse/core';
  import { useAppStore, useUserStore } from '@/store';
  import { LOCALE_OPTIONS } from '@/locale';
  import useLocale from '@/hooks/locale';
  import useUser from '@/hooks/user';
  import Menu from '@/components/menu/index.vue';
  import { upUser } from '@/api/user';
  const uploadForm = ref({
    oldPassword: '',
    newPassword: '',
    nnewPassword: '',
  });
  import useLoading from '@/hooks/loading';
  const { loading, setLoading } = useLoading(true);
  const uploadShow = ref(false);
  const appStore = useAppStore();
  const userStore = useUserStore();
  const { logout } = useUser();
  const { changeLocale, currentLocale } = useLocale();
  const { isFullscreen, toggle: toggleFullScreen } = useFullscreen();
  const locales = [...LOCALE_OPTIONS];
  const theme = computed(() => {
    return appStore.theme;
  });
  const topMenu = computed(() => appStore.topMenu && appStore.menu);
  const keepDesktop = computed(() => appStore.keepDesktop);
  const isDark = useDark({
    selector: 'body',
    attribute: 'arco-theme',
    valueDark: 'dark',
    valueLight: 'light',
    storageKey: 'arco-theme',
    onChanged(dark: boolean) {
      // overridden default behavior
      // appStore.toggleTheme(dark);
    },
  });
  const uploadCancel = () => {
    uploadForm.value = [];
    byyshow.value = false;
    uploadShow.value = false;
  };

  const byyshow = ref(false);
  // 二次输入密码校验
  const uploadModel = ref();
  const erpassfn = (value) => {
    uploadModel.value.validateField('nnewPassword', (errorMessage) => {
      if (!errorMessage) {
        console.log('通过校验');
        if (uploadForm.value.nnewPassword != '') {
          if (value != uploadForm.value.newPassword) {
            byyshow.value = true;
          } else {
            byyshow.value = false;
          }
        }
      }
    });
  };
  const uploadCheck = (done) => {
    // if (loading.value) {
    //   done(false);
    //   return;
    // }
    console.log('执行了3', byyshow.value);
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 1500);
    console.log('执行了1', byyshow.value);
    uploadModel.value.validate(
      async (errors: undefined | Record<string, ValidatedError>) => {
        console.log('执行了', errors, byyshow.value);
        if (!errors && !byyshow.value) {
          upUser(uploadForm.value).then((res) => {
            if (res.code == '200') {
              Message.success({
                //   content: res.message,
                content: '修改成功!',
              });
              uploadForm.value = [];
              byyshow.value = false;
              uploadShow.value = false;
              handleLogout();
              done(true);
            } else {
              Message.success({
                //   content: res.message,
                content: res.message,
              });
              done(false);
            }
          });
        } else {
          done(false);
        }
      }
    );
  };
  const uploadRules = {
    //  /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!#$%^&*])[\da-zA-Z!#$%^&*]{8,16}$/

    oldPassword: [
      {
        required: true,
        message: '请输入旧密码',
      },
    ],
    newPassword: [
      {
        required: true,
        message: '请输入新密码',
      },
      {
        match: /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[!@#$%^&*?])[^\s]{6,16}$/,
        // /^\S*(?=\S{6,})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[!@#$%^&*? ])\S*$/,
        message: '6-16位的,需包含大写字母、小写字母、特殊符号及数字',
      },
    ],
    nnewPassword: [
      {
        required: true,
        message: '请输入新密码',
      },
      {
        match: /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[!@#$%^&*?])[^\s]{6,16}$/,
        message: '6-16位的,需包含大写字母、小写字母、特殊符号及数字',
      },
    ],
  };
  const toggleTheme = useToggle(isDark);
  const handleToggleTheme = () => {
    toggleTheme();
  };
  const setVisible = () => {
    appStore.updateSettings({
      globalSettings: true,
    });
  };
  const refBtn = ref();
  const triggerBtn = ref();
  const setPopoverVisible = () => {
    const event = new MouseEvent('click', {
      view: window,
      bubbles: true,
      cancelable: true,
    });
    refBtn.value.dispatchEvent(event);
  };
  const handleLogout = () => {
    logout();
  };
  const setDropDownVisible = () => {
    const event = new MouseEvent('click', {
      view: window,
      bubbles: true,
      cancelable: true,
    });
    triggerBtn.value.dispatchEvent(event);
  };
  const switchRoles = async () => {
    const res = await userStore.switchRoles();
    Message.success(res as string);
  };
  const toggleDrawerMenu = inject('toggleDrawerMenu') as () => void;
</script>

<style scoped lang="less">
  .navbar {
    display: flex;
    justify-content: space-between;
    height: 100%;
    background-color: var(--color-bg-2);
    border-bottom: 1px solid var(--color-border);
  }

  .left-side {
    display: flex;
    align-items: center;
    padding-left: 20px;
  }

  .center-side {
    flex: 1;
  }

  .right-side {
    display: flex;
    padding-right: 20px;
    list-style: none;
    :deep(.locale-select) {
      border-radius: 20px;
    }
    li {
      display: flex;
      align-items: center;
      padding: 0 10px;
    }
    a {
      color: var(--color-text-1);
      text-decoration: none;
    }
    .nav-btn {
      border-color: rgb(var(--gray-2));
      color: rgb(var(--gray-8));
      font-size: 16px;
    }
    .trigger-btn,
    .ref-btn {
      position: absolute;
      bottom: 14px;
    }
    .trigger-btn {
      margin-left: 14px;
    }
  }
</style>

<style lang="less">
  .message-popover {
    .arco-popover-content {
      margin-top: 0;
    }
  }
  .lc {
    color: red;
    font-size: 12px;
    text-align: center;
    display: flex;
    align-items: center;
    margin: 0 auto;
  }
</style>
